<script setup>
import {computed, onMounted, reactive, ref, shallowRef} from "vue";
import _ from "lodash";
import {readExcel, useAntTableScroll} from "@/utils";
import {message} from "ant-design-vue";
import {getAdvanceNoticeDays, getStartRowOfImport} from "@/utils/setting";
import dayjs from 'dayjs'

const dangerValue = ref(-7)
const searchForm = ref({})
const pageParams = ref({ pageNum: 1, pageSize: 10 })
const total = shallowRef(0)
const tableRef = shallowRef()
const tableScroll = useAntTableScroll(tableRef)
const onlyShowWarnData = shallowRef(false)
/**
 * @type {import('vue').Reactive<import('ant-design-vue').TableProps['rowSelection']>}
 */
const tableSelection = reactive({
  selectedRowKeys: [],
  onChange(keys) {
    tableSelection.selectedRowKeys = keys
  }
})

const pageConfig = computed(() => ({
  total: total.value,
  current: pageParams.value.pageNum,
  pageSize: pageParams.value.pageSize,
  onChange(page, size) {
    pageParams.value.pageNum = page
    pageParams.value.pageSize = size
    loadData()
  },
  showTotal(total, range) {
    return `总共${total}条，当前显示${range.join('-')}`
  }
}))
const loading = shallowRef(false)
const tableData = ref([])

const delDisabled = computed(() => tableSelection.selectedRowKeys.length === 0);

function loadData() {
  loading.value = true
  window.asset.getPagedList(_.cloneDeep(searchForm.value), _.cloneDeep(pageParams.value), onlyShowWarnData.value).then((data) => {
    const { count, rows } = data
    tableData.value = rows.map(({ dataValues }) => dataValues)
    total.value = count
  }).finally(() => {
    loading.value = false
  })
}


const headerAlias = [
  null,
  'id',
  'name',
  'spec',
  'accuracy',
  'manufacturer',
  'factoryNumber',
  'traceabilityMethod',
  'calibrationParameters',
  'traceabilityDate',
  'nextTraceabilityDate',
  'traceabilityConclusion',
  'traceabilityInstitution',
  'certificateNumber',
  'remark'
]

function handleImport() {
  let hide = message.loading('正在选择文件', 0);
  getStartRowOfImport()
      .then((data) => readExcel({
        header: 1,
        blankrows: false,
        startRow: Number(data.value),
        raw: false,
        dateNF: 'yyyy-mm-dd'
      }))
      .then(data => {
        hide()
        hide = message.loading('正在解析文件', 0)
        const arr = data.map((row) => {
          const data = {}
          headerAlias.forEach((item, index) => {
            if (item == null || row[index] == null) {
              return
            }
            data[item] = row[index]
          })
          return data
        }).filter(item => item.id != null)
        hide()
        return arr
      })
      .then(async (data) => {
        hide = message.loading('正在导入数据', 0)
        await window.asset.saveBatch(data)
        message.success('导入成功')
        hide()
      })
      .then(() => {
        loadData()
      })
      .finally(() => {
        hide && hide()
      })
}

function handleRowClassName(row) {
  const number = dayjs().diff(row.nextTraceabilityDate, 'day');
  console.log(number, dayjs().format('YYYY/MM/DD'), row.nextTraceabilityDate.toLocaleDateString())
  const danger = number > dangerValue.value;
  return ['_1', { danger: danger, safe: !danger }]
}

function handleSearch() {
  pageParams.value.pageNum = 1
  loadData()
}

function handleReset() {
  pageParams.value.pageNum = 1
  searchForm.value = {}
  loadData()
}

onMounted(() => {
  getAdvanceNoticeDays().then((data) => {
    dangerValue.value = -Number(data.value)
  })
  loadData()
})

</script>

<template>
  <div class="page">
    <a-flex class="h-100" vertical gap="small">
      <a-form layout="inline">
        <a-form-item>
          <a-input v-model:value="searchForm.name" placeholder="设备/器具/标准物质名称"/>
        </a-form-item>
        <a-form-item>
          <a-input v-model:value="searchForm.specification" placeholder="规格型号"/>
        </a-form-item>
        <a-form-item label="仅显示警告期数据">
          <a-checkbox v-model:checked="onlyShowWarnData"/>
        </a-form-item>
        <a-form-item>
          <a-flex gap="small">
            <a-button type="primary" @click="handleSearch">
              <template #icon>
                <SearchOutlined/>
              </template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon>
                <ReloadOutlined/>
              </template>
              重置
            </a-button>
          </a-flex>
        </a-form-item>
      </a-form>

      <a-card class="flex-1">
        <a-flex class="h-100" vertical gap="small">
          <a-flex gap="small">
            <a-button type="primary" @click="handleImport">
              <template #icon>
                <DownloadOutlined/>
              </template>
              导入数据
            </a-button>
            <a-button type="primary" danger :disabled="delDisabled">
              <template #icon>
                <DeleteOutlined/>
              </template>
              删除
            </a-button>
          </a-flex>
          <a-table ref="tableRef" class="flex-1 rewrite" row-key="id" table-layout="fixed" :scroll="tableScroll"
                   :row-class-name="handleRowClassName"
                   :data-source="tableData"
                   :loading="loading"
                   :row-selection="tableSelection"
                   :pagination="pageConfig">
            <a-table-column title="序号">
              <template #customRender="{index}">
                {{ (pageConfig.current - 1) * pageConfig.pageSize + index + 1 }}
              </template>
            </a-table-column>
            <a-table-column :width="150" data-index="id" title="自编号"/>
            <a-table-column :width="200" data-index="name" title="设备/器具/标准物质名称"/>
            <a-table-column :width="150" data-index="spec" title="规格型号"/>
            <a-table-column :width="150" data-index="accuracy" title="精度/等级"/>
            <a-table-column :width="150" data-index="manufacturer" title="生产厂家"/>
            <a-table-column :width="150" data-index="factoryNumber" title="出厂编号"/>
            <a-table-column :width="150" data-index="traceabilityMethod" title="溯源方式"/>
            <a-table-column :width="200" data-index="calibrationParameters"
                            title="校准参数（方法要求）"/>
            <a-table-column :width="150" data-index="traceabilityDate" title="量值溯源日期">
              <template #customRender="{record}">
                {{ record.traceabilityDate.toLocaleDateString() }}
              </template>
            </a-table-column>
            <a-table-column :width="200" data-index="nextTraceabilityDate" title="拟下次溯源日期（前）">
              <template #customRender="{record}">
                {{ record.nextTraceabilityDate.toLocaleDateString() }}
              </template>
            </a-table-column>
            <a-table-column :width="150" data-index="traceabilityConclusion" title="溯源结论"/>
            <a-table-column :width="150" data-index="traceabilityInstitution" title="溯源实施机构"/>
            <a-table-column :width="150" data-index="certificateNumber" title="证书编号"/>
            <a-table-column :width="150" data-index="remark" title="备注"/>
          </a-table>
        </a-flex>
      </a-card>

    </a-flex>

  </div>
</template>

<style scoped>

</style>
